// Copyright 2009 StarCite Inc.  All rights reserved.
// MongoDBUtil.java 1:55:26 PM danny.liu
package com.billowsoft.blog.dao;

import java.util.HashMap;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;

import com.mongodb.BasicDBObject;

/**
 * @author danny.liu Jun 25, 2012
 * @version 1.0
 * 
 */
public final class MongoDBUtil {

	public static String constructLessThanEqualCriteria(Object value) {
		return String.format(" { $lte: %s }", value.toString());
	}

	public static <T> BasicDBObject convertObjectToMongoObject(T obj) {

		BasicDBObject mongoObject = null;

		if (obj instanceof Map) {
			mongoObject = new BasicDBObject((Map) obj);
		} else {
			ObjectMapper mapper = new ObjectMapper();
			try {
				String jsonString = mapper.writeValueAsString(obj);
				HashMap<String, Object> result = new ObjectMapper().readValue(
						jsonString, HashMap.class);
				mongoObject = new BasicDBObject(result);
			} catch (Exception e) {
				System.out.println("Failed: " + e.getMessage());
			}
		}

		return mongoObject;
	}

}
